<?php
	require_once('NetflixQueueItem.php');
	require_once('NetflixTitle.php');
	
	define("QUEUE_TYPE_DISC", "disc");
	define("QUEUE_TYPE_INSTANT", "instant");
	define("QUEUE_TYPE_SAVED", "saved");
	define("QUEUE_GET_MAX_RESULTS", 500);

  class NetflixQueue {
	public $id;
	private $netflix;
	
	public $queueName;
	public $queueSize;
	public $queueType; //"disc" or "instant" or "saved"
	public $queueLink;
	public $queueItems = array(); //list of netflix queue Items
	public $etag;
	
	function __construct($userId, $queueType=QUEUE_TYPE_INSTANT, $netflix) {
		$this->userId = $userId;
		$this->queueName = $queueName;
		$this->setQueueType($queueType);
		
		$this->netflix = $netflix;
		
		$this->saveToDB();
		
		$this->refreshQueueItems();
	}
	
	function refreshQueueItems(){
		$feed_url = $this->getQueueURL();
		if($feed_url == NULL){
		    echo "Error in refreshQueueItems--Could not get URL for queue";
		    return NULL;
		}
		$access_params = $this->netflix->getAccessParams();		
		$itemsFetched = 0;
		$this->clearLocalQueueItems();
		
		while(TRUE){
			$access_params['start_index'] = $itemsFetched;
			$access_params['max_results'] = 25;			
			$authURL = $this->netflix->createAuthorizedURL($feed_url, "GET", $access_params);
			$xml = getURLAsString($authURL);
			
			if($xml){
				$xmlObject = new SimpleXMLElement($xml);
				$this->etag= $xmlObject->etag;

				$queueItems = $xmlObject->xpath('/queue/queue_item');
				foreach($queueItems as $index => $queueItem){
					$queuePosition = $itemsFetched + $index + 1;
					$netflixTitle = new NetflixTitle($queueItem->asXML());
					$netflixQueueItem = new NetflixQueueItem($this, $queuePosition, $netflixTitle);
					$this->queueItems[] = $netflixQueueItem;
				}

				$resultsPerPage = $xmlObject->xpath("/queue/results_per_page");
				$resultsPerPage = $resultsPerPage[0];
				$queueSize = $xmlObject->xpath("/queue/number_of_results");
				$queueSize = $queueSize[0];		
				$itemsFetched += $resultsPerPage;
				if($itemsFetched == $queueSize){
					$this->queueSize = $queueSize;
					break;
				}
			}
		}
	}
	
	function saveToDB($queueName = ''){
		$insertQuery = "INSERT INTO queue (`user_id`, `name`, `queue_type`) 
						VALUES ('{$this->userId}', '{$queueName}', '{$this->queueType}')";
	
		$insertResult = mysql_query($insertQuery) or die ("Error inserting queue with query $insertResult");
		
		$this->id = mysql_insert_id();

		$this->saveQueueItemsToDB($this->id);
	}

	private function saveQueueItemsToDB($queueId){
		foreach($this->queueItems as $item){
			$item->saveToDb($queueId);
		}
	}	
	
	function clearQueue(){
	     clearLocalQueueItems();
	     clearDBQueueItems();
	}
	
	function clearLocalQueueItems(){
	     $this->queueSize = 0;
	     $this->queueItems = array();
	}
	
	function clearDBQueueItems(){
		$clear_query = "DELETE FROM queue_item where queue_id = $this->queueDBId";
		mysql_query($clear_query);
	}
	

	function isStale(){
		if($this->etag !== $this->getEtagFromNetflix()){
			return true;
		}
		
		return false;
	}
	
	function getEtagFromNetflix(){
		$feed_url = $this->getQueueURL();
		if($feed_url == NULL){
		    echo "Error in refreshQueueItems--Could not get URL for queue";
		    return NULL;
		}
		
		$access_params = $this->netflix->getAccessParams();		
		$access_params['start_index'] = $itemsFetched;
		$access_params['max_results'] = 25;			
		$authURL = $this->netflix->createAuthorizedURL($feed_url, "GET", $access_params);
		$xml = getURLAsString($authURL);

		if($xml){
			$xml = new SimpleXMLElement($xml);
			$etag= $xml->etag;
			fb($etag, 'etag of queue from netflix');
			return $etag;
		}
		
		return null;
	}
			
	function dequeue(){
/*
	     //Deletes the first item from the queue
	     $queue_item= $this->queueItems[0];
	     
	     if($queue_item != NULL){
			$url = $queue_item->queueId;
			$method = "DELETE";
			$access_params = $this->netflix->getAccessParams();
			echo "Access params are :<br />";
			print_r($access_params);
			$authURL = $this->netflix->createAuthorizedURL($url, $method, $access_params);
			echo "Queue item url to delete is $authURL";
			$response= getURLAsString($authURL, $method);
			echo "<br />Response to deleting item is $response<br />";
		}      	
*/
	}
	
	function enqueue($titleURL){
	     $method = "POST";
	     $url = $this->getQueueURL();
	     $params = $this->netflix->getAccessParams();
	     $params['title_ref'] = $titleURL;
	     $params['method'] = $method;
	     $params['position'] = $this->queueSize + 1;
	     $params['etag'] = $this->etag;
	     $authURL= $this->netflix->createAuthorizedURL($url,$method,$params);
	     //echo "enqueue authURL is $authURL<br/>";
	     //exit();
	     $response= postURLAsString($authURL, $params);
	     if($response != NULL){
	           echo "Response is : <br />";
	           print_r($response);
	           $xml= new SimpleXMLElement($response);
	           $this->etag=$xml->etag;
	           $this->saveEtag();
	     }
	     
	}
	
	function setQueueType($type){
		switch($type):
		case QUEUE_TYPE_DISC:			
		case QUEUE_TYPE_INSTANT:
		case QUEUE_TYPE_SAVED:
			$this->queueType = $type;
			break;
		default:
			echo "Invalid queue type \"$type\" provided to setQueueType(...)";
			break;
		endswitch;
			
	}

	function getQueueURL(){
		switch($this->queueType):
			case QUEUE_TYPE_DISC:
				return $this->getQueueURLDisc();
				break;
			case QUEUE_TYPE_INSTANT:
				return $this->getQueueURLInstant();
				break;
			case QUEUE_TYPE_SAVED:
				return $this->getQueueURLSaved();
				break;
			default:
				return NULL;
				break;
			endswitch;
	}
	function getQueueURLDisc(){
		if($this->netflix->getUserId()){
			return "http://api.netflix.com/users/" . $this->netflix->getUserId() . "/queues/disc";
		}
		
		else{
			echo "User ID not set, cant create a valid URL for Disc Queue<br />";
			return null;
		}
	}
	function getQueueURLInstant(){
		if($this->netflix->getUserId()){
			return "http://api.netflix.com/users/" . $this->netflix->getUserId() . "/queues/instant";
		}
		else return null;
	}
	
	function getQueueURLSaved(){
		if($this->netflix->getUserId()){
			return "http://api.netflix.com/users/" . $this->netflix->getUserId() . "/queues/saved";
		}
		else return null;
	}
	
	function toString(){
		$string = '';
		foreach($this->queueItems as $item){
			$string .= $item->toString();
			$string .= '<br/>';
		}
		
		return $string;
	}
	
}
	
?>
